package it.asvp.asvp_portal.service.services.impl;

import it.asvp.asvp_portal.data.dao.ArtDao;
import it.asvp.asvp_portal.data.dao.ArtPictureDao;
import it.asvp.asvp_portal.data.dao.MemberAccountDao;
import it.asvp.asvp_portal.data.dao.MemberDao;
import it.asvp.asvp_portal.data.entity.art.Art;
import it.asvp.asvp_portal.data.entity.art.ArtPicture;
import it.asvp.asvp_portal.data.entity.member.Member;
import it.asvp.asvp_portal.data.entity.member.MemberAccount;
import it.asvp.asvp_portal.service.services.ArtService;
import it.asvp.asvp_portal.service.services.MemberAccountService;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ArtServiceImpl implements ArtService{

	@Autowired
	ArtDao artDao;
	@Autowired
	ArtPictureDao artPictureDao;
	@Autowired
	MemberDao memberDao;
	@Autowired
	MemberAccountDao memberAccountDao;
	@Autowired
	MemberAccountService memberAccountService;
	
	@Transactional
	@Rollback
	public Long addArt(UserDetails userDetails,Art transientArt) throws Exception{
	
		MemberAccount persistentCurrentAccount=memberAccountDao.findByLogin(userDetails.getUsername());
		  
		if(persistentCurrentAccount==null){
				throw new Exception("Account errato");
		}
		
		Member persistentMember=persistentCurrentAccount.getMember();
		transientArt.setMember(persistentMember);
		return artDao.persist(transientArt);
	}
	
	@Transactional
	@Rollback
	public List<Art> getAllArts(){
		
		List<Art> allArts=artDao.findAll();
		return allArts;
	}
	
	@Transactional
	@Rollback
	public Art getById(Long idArt) throws Exception{
		
		  Art persistentArt=artDao.findById(idArt);
		  if(persistentArt==null){
			  throw new Exception("Art non presente");
		  }
		  return persistentArt;
	}
	
	@Transactional
	@Rollback
	private void updatePictures(Long idArt, Set<ArtPicture> oldArtPictures,Set<ArtPicture> newArtPictures){
		
		for(ArtPicture artPicture:oldArtPictures){
			artPictureDao.delete(artPicture);
		}
		
		for(ArtPicture artPicture:newArtPictures){
			artPicture.setId(idArt);
			artPictureDao.persist(artPicture);
		}
	}
}
